from pytoss import *

example_machine = Role("$") # try it with your own remote machines!

@task
def show_procs():
    """shows all processes running on the example machine"""
    example_machine.run("ps aux")

@task
def ping_google():
    """pings Google 5 times, demonstrating pytoss' live output"""
    example_machine.run("ping -c 5 www.gooogle.com")

@task
def interactive_remove():
    """creates a file and then tries to remove it interactively"""
    example_machine.expect_input_for("remove.*\?.*$")
    example_machine.run("touch deleteme")
    example_machine.run("rm -i deleteme")
    log("""
        about to list files
        depending on how you answered the prompt,
        you may see the file named 'deleteme'
    """)
    example_machine.stop_expecting("remove.*\?.*$")
    example_machine.run("ls")

@task
def bash_script():
    """runs a simple bash script that outputs hello_world"""
    bash_script = """
        #!/bin/bash
        if [ "foo" = "foo" ]; then
           echo hello_world
        else
           echo goodbye
        fi
    """
    result = example_machine.run(bash_script)
    for key in result:
        if result[key].strip() == "hello_world":
            log("the bash script responded positively on %s" % key)

@task
def undoable_mkdir():
    """demonstrates the rollback ability of tasks
    by creating a directory and removing it when
    an exception occurrs"""
    db.run("mkdir deleteme")
    register_rollback(lambda: db.run("rmdir deleteme"))
    log("""
        just made directory 'deleteme', but we're about to throw an exception
        you should see it get rolled back with rmdir
    """)
    raise RuntimeError("something bad happened!")

